package com.yiwei.zxp.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.CircleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.UploadImgBean;
import com.yiwei.zxp.api.bean.UserEditBean;
import com.yiwei.zxp.api.model.UserInfoModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.LoginSuccessEvent;
import com.yiwei.zxp.util.ImageUtil;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.V19FrameLayout;
import com.yiwei.zxp.view.uploadImage.UploadImgAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class PersonalCenterActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.btn_icon)
    LinearLayout btnIcon;
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.btn_phone)
    LinearLayout btnPhone;
    @BindView(R.id.txt_nickname)
    TextView txtNickname;
    @BindView(R.id.btn_nickname)
    LinearLayout btnNickname;
    @BindView(R.id.img_nickname_right)
    ImageView imgNicknameRight;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.img_address_right)
    ImageView imgAddressRight;
    @BindView(R.id.btn_address)
    LinearLayout btnAddress;
    @BindView(R.id.txt_invite_code)
    TextView txtInviteCode;
    @BindView(R.id.img_invite_code_right)
    ImageView imgInviteCodeRight;
    @BindView(R.id.btn_invite_code)
    LinearLayout btnInviteCode;
    @BindView(R.id.txt_commission)
    TextView txtCommission;
    @BindView(R.id.img_commission_right)
    ImageView imgCommissionRight;
    @BindView(R.id.btn_commission)
    LinearLayout btnCommission;
    @BindView(R.id.img_qrcode_right)
    ImageView imgQrcodeRight;
    @BindView(R.id.btn_qrcode)
    LinearLayout btnQrcode;
    private Unbinder unbiner;
    private UploadImgAdapter uploadImgAdapter;
    private UserInfoModel.DatasBean userdata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_center);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
//        txtRight.setText("保存");
//        txtRight.setVisibility(View.VISIBLE);
        txtTitle.setText("个人资料");
        Glide.with(this).load(UserInfoGlobal.getIcon()).asBitmap().error(R.mipmap.img_my_default).into(imgIcon);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUser();
    }

    private void goToTakePhoto() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (uploadImgAdapter == null) {
                    initUploadImgAdapter();
                }
                uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImg(file);

                }
            }

            @Override
            public void callTake(File file, int mode) {
                Glide.with(PersonalCenterActivity.this).load(file).asBitmap().into(new SimpleTarget<Bitmap>(300, 300) {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        getUploadImg(resource);
                    }
                });
            }
        }, 1);
    }

    public void getUserEdit(String key, String value) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UserEditBean bean = new UserEditBean();
        bean.keyword = key;
        bean.value = value;
        Api.api_service.getUserEdit(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "修改成功");
                    if (key.equals("username")) {
                        EventBus.getDefault().post(new LoginSuccessEvent());
                        finish();
                    }
                });
    }

    public void getInviteCode() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getSetInvitecode().compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    ToastUtil.makeText(this, "恭喜你，邀请码生成成功");
                    UserInfoGlobal.setInviteCode(result.datas.invite_code);
                    imgInviteCodeRight.setVisibility(View.INVISIBLE);
                    txtInviteCode.setText(result.datas.invite_code);
                });
    }


    public void getUser() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        Api.api_service.getUserInfo().compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        UserInfoModel.DatasBean item = result.datas;
                        txtPhone.setText(item.phone);//手机号
                        if (!TextUtils.isEmpty(item.username)) {
                            txtNickname.setText(item.username);//昵称
//                            imgNicknameRight.setVisibility(View.INVISIBLE);
                        }

                        if (!TextUtils.isEmpty(item.invite_code)) {
                            txtInviteCode.setText(item.invite_code);//邀请码
                            imgInviteCodeRight.setVisibility(View.INVISIBLE);
                        }

                        StringBuilder builder = new StringBuilder();
                        if (item.province != null) {
                            if (!TextUtils.isEmpty(item.province.name)) {
                                builder.append(item.province.name);
                            }
                        }
                        if (item.city != null) {
                            if (!TextUtils.isEmpty(item.city.name)) {
                                builder.append(item.city.name);
                            }
                        }
                        if (item.district != null) {
                            if (!TextUtils.isEmpty(item.district.name)) {
                                builder.append(item.district.name);
                            }
                        }
                        if (builder.length() != 0) {
                            imgAddressRight.setVisibility(View.INVISIBLE);
                            txtAddress.setText(builder.toString());//省市区
                        }

                        userdata = result.datas;
                        Glide.with(this).load(item.icon).asBitmap().into(imgIcon);//头像
                    }
                });
    }


    public void getUploadImg(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.getUploadImg(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    imgIcon.setImageBitmap(bitmap);

                    getUserEdit("icon", result.datas.short_url);
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.txt_right, R.id.img_icon})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                if (TextUtils.isEmpty(UI.toString(txtNickname))) {
                    ToastUtil.makeText(this, "你尚未设置用户名");
                    return;
                }
                getUserEdit("username", UI.toString(txtNickname));
                break;
            case R.id.img_icon:
                goToTakePhoto();
                break;
        }
    }

    @OnClick({R.id.txt_nickname, R.id.txt_address, R.id.txt_invite_code, R.id.btn_commission, R.id.btn_qrcode})
    public void onViewClicked1(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.txt_nickname:
                Util.startActivity(this, NickNameActivity.class);
                break;
            case R.id.txt_address:
                if (!TextUtils.isEmpty(UI.toString(txtAddress))) {
                    ToastUtil.makeText(this, "您已设置过常用居住地");
                    return;
                }
                Util.startActivity(this, MyAddressSetActivity.class);
                break;
            case R.id.txt_invite_code:
                if (TextUtils.isEmpty(UI.toString(txtInviteCode))) {
                    getInviteCode();
                }
                break;
            case R.id.btn_commission:
                if (userdata == null) {
                    return;
                }
                if (!TextUtils.isEmpty(userdata.invite_id)) {
                    Util.startActivity(this, MyRefereeActivity.class);
                } else {
                    Util.startActivity(this, MySetRefereeActivity.class);
                }
                break;
            case R.id.btn_qrcode:
                Util.startActivity(this, MyQrCodeActivity.class);
                break;
        }
    }
}
